﻿using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
using ChatModel;
using System;
using MetroJabbViewModel.Types;

namespace MetroJabbViewModel
{
    public class ChatViewModel : INotifyPropertyChanged
    {
        private readonly ChatFacade _chat;
        private bool _isConnected;
        private ICommand _connectCommand;
        private ICommand _sendMessageCommand;

        public ChatViewModel(string chatServerUrl, string chatHub, IUserDataStore userDataStore)
        {
            _chat = new ChatFacade(chatServerUrl, chatHub, userDataStore);
            _chat.Connected += () => IsConnected = true;
            _chat.Disconnected += () => IsConnected = false;

            _connectCommand = new RelayCommand(Connect, CanConnect);
            _sendMessageCommand = new RelayCommand<string>(SendMessage, CanSendMessage);
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public bool IsConnected
        {
            get
            {
                return _isConnected;
            }
            set
            {
                if (_isConnected != value)
                {
                    _isConnected = value;
                    OnPropertyChanged("IsConnected");
                }
            }
        }

        public ObservableCollection<Room> Rooms
        {
            get
            {
                return _chat.Rooms;
            }
        }

        public ObservableCollection<User> Users
        {
            get
            {
                return _chat.Users;
            }
        }

        #region Connect command

        public ICommand ConnectCommand
        {
            get { return _connectCommand; }
        }

        private void Connect()
        {
            _chat.Connect();
        }

        private bool CanConnect()
        {
            return !IsConnected;
        }

        #endregion

        #region SendMessage command 

        public ICommand SendMessageCommand
        {
            get
            {
                return _sendMessageCommand;
            }
        }

        private void SendMessage(string message)
        {
            _chat.Send(message);
        }

        private bool CanSendMessage(string message)
        {
            return IsConnected && !String.IsNullOrEmpty(message);
        }

        #endregion

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}